<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import SlidingCard from "@/components/SlidingCard.vue";
import Layer from "./components/Layer.vue";
import liveTime from "./components/LiveTime.vue";
import navItem from "./components/NavItem.vue";
import TimeItem from "./components/TimeItem.vue";
// 导入图标
import blog from "@/assets/icon/blog.png";
import cloudDisk from "@/assets/icon/cloudDisk.png";
import music from "@/assets/icon/music.png";
import startPage from "@/assets/icon/startPage.png";
import hotList from "@/assets/icon/hotList.png";
import collect from "@/assets/icon/collect.png";
import closeIcon from "@/assets/icon/close.png";
import hourglass from "@/assets/icon/hourglass.png";
import { TimeInfo } from "@/types/home";

const router = useRouter();

// 导航到指定路由
function navigateTo(url: string) {
  router.push(url);
}

const cards = [
  "http://192.168.203.132:9090/media-bao/2024/12/19/IMG_20230403_181113.jpg",
  "http://192.168.203.132:9090/media-bao/2024/12/19/IMG_20230404_074519.jpg",
  "http://192.168.203.132:9090/media-bao/2025/03/07/d0786137dc2dba85ab0cc1ccb02284f731c3c137099848019dfd3497282a2a0a.png",
  "http://192.168.203.132:9090/media-bao/2025/03/10/081119cbd6337661c16d445cd2c238b89b3820b389ed3a5c9dd802ae5015ec4b.png",
  "http://192.168.203.132:9090/media-bao/2025/03/10/a93330a0e8ea47a51c7c1b6cc7bcfa65ba557fc7b42af7d4e501984e6b038d45.png",

  // 添加更多卡片...
];
//联系方式数组
const homeIcons = ref([
  { title: "博客", icon: blog, url: "/blog" },
  { title: "网盘", icon: cloudDisk, url: "/blog" },
  { title: "音乐", icon: music, url: "/blog" },
  { title: "起始页", icon: startPage, url: "/blog" },
  { title: "网址", icon: collect, url: "/blog" },
  { title: "热点", icon: hotList, url: "/blog" },
]);
// 时间模块的显示
let timeFlag = ref(true);

//-----------start 滑动阻尼

// 定义滚动容器元素和滚动位置变量
let scrollbox: HTMLElement | null = null;
let targetScrollY = 0; // 目标滚动位置
let currentScrollY = 0; // 当前滚动位置

const showScrollButton = ref(true);

// 判断是否应该隐藏按钮
function checkScrollVisibility() {
  const target = document.querySelector(".full-page-div.rounded-2xl") as HTMLElement;
  if (target && scrollbox) {
    const targetBottom = target.offsetTop + target.offsetHeight;
    showScrollButton.value = currentScrollY < targetBottom;
  }
}
// 动画滚动函数
function animateScroll() {
  const diff = targetScrollY - currentScrollY;
  if (Math.abs(diff) > 0.5) {
    // 计算新的滚动位置（阻尼效果）
    currentScrollY += diff * 0.1; // 阻尼系数
    limitCurrentScroll(); // 限制滚动范围
    applyTransform(); // 应用变换
    checkScrollVisibility();
    requestAnimationFrame(animateScroll); // 继续动画
  } else {
    // 如果差值很小，直接设置为目标位置
    currentScrollY = targetScrollY;
    applyTransform(); // 应用变换
    checkScrollVisibility(); // 添加此行
  }
}

// 应用滚动变换到元素上
function applyTransform() {
  if (scrollbox) {
    scrollbox.style.transform = `translateY(${-currentScrollY}px)`;
  }
}

// 获取最大滚动值
function getMaxScroll(): number {
  if (!scrollbox) return 0;
  return scrollbox.scrollHeight - window.innerHeight;
}

// 限制目标滚动位置在有效范围内
function limitTargetScroll() {
  const maxScroll = getMaxScroll();
  targetScrollY = Math.max(0, Math.min(targetScrollY, maxScroll));
}

// 限制当前滚动位置在有效范围内
function limitCurrentScroll() {
  const maxScroll = getMaxScroll();
  currentScrollY = Math.max(0, Math.min(currentScrollY, maxScroll));
}

// 处理鼠标滚轮事件
function handleScroll(event: WheelEvent) {
  event.preventDefault(); // 阻止默认滚动
  targetScrollY += event.deltaY;
  limitTargetScroll();
  requestAnimationFrame(animateScroll);
}

// 触控开始相关变量
let touchStartY = 0;
let touchLastY = 0;
let touchStartTime = 0;
let isTouching = false;

// 触控开始事件处理
function handleTouchStart(event: TouchEvent) {
  if (event.touches.length !== 1) return;
  const touch = event.touches[0];
  touchStartY = touch.clientY;
  touchLastY = touch.clientY;
  touchStartTime = Date.now();
  isTouching = true;
}

// 触控移动事件处理
function handleTouchMove(event: TouchEvent) {
  if (!isTouching || event.touches.length !== 1) return;
  const touch = event.touches[0];
  const delta = touch.clientY - touchLastY;
  touchLastY = touch.clientY;

  targetScrollY -= delta;
  limitTargetScroll();
  requestAnimationFrame(animateScroll);
}

// 触控结束（惯性滚动）事件处理
function handleTouchEnd(event: TouchEvent) {
  if (!isTouching) return;

  const touch = event.changedTouches[0];
  const deltaY = touch.clientY - touchStartY;
  const duration = Date.now() - touchStartTime;

  const velocity = deltaY / duration;
  if (Math.abs(velocity) > 0.3) {
    targetScrollY -= deltaY * 2; // 加入惯性位移
    limitTargetScroll();
    requestAnimationFrame(animateScroll);
  }

  isTouching = false;
}

const init = () => {
  scrollbox = document.querySelector(".scrollbox");
  if (scrollbox) {
    document.body.style.height = `${scrollbox.scrollHeight}px`;

    // 恢复上次的滚动位置
    const savedScrollY = localStorage.getItem("customScrollY");
    if (savedScrollY) {
      currentScrollY = parseInt(savedScrollY, 10);
      targetScrollY = currentScrollY;
      applyTransform();
    }
  }

  window.addEventListener("resize", () => {
    if (scrollbox) {
      document.body.style.height = `${scrollbox.scrollHeight}px`;
    }
  });

  window.addEventListener("wheel", handleScroll, { passive: false });
  window.addEventListener("touchstart", handleTouchStart, { passive: true });
  window.addEventListener("touchmove", handleTouchMove, { passive: false });
  window.addEventListener("touchend", handleTouchEnd, { passive: true });

  // 页面隐藏或刷新前保存滚动位置
  window.addEventListener("beforeunload", () => {
    localStorage.setItem("customScrollY", currentScrollY.toString());
  });
};

// 联系文字
const hoverText = ref<String>("");
//枚举类型 0 1 2 3 4 5 对应：qq 微信、邮箱、B站、gitee
enum ContactType {
  QQ = 1,
  WX = 2,
  // eslint-disable-next-line no-unused-vars
  Email = 3,
  // eslint-disable-next-line no-unused-vars
  Bilibili = 4,
  // eslint-disable-next-line no-unused-vars
  Gitee = 5,
  // eslint-disable-next-line no-unused-vars
  Other = 6,
}

function handleHover(index: number) {
  switch (index) {
    case ContactType.QQ:
      hoverText.value = "QQ: 1234567890";
      break;
    case ContactType.WX:
      hoverText.value = "微信: 1234567890";
      break;
    case ContactType.Email:
      hoverText.value = "邮箱: 1234567890@qq.com";
      break;
    case ContactType.Bilibili:
      hoverText.value = "B站: 1234567890";
      break;
    case ContactType.Gitee:
      hoverText.value = "Gitee: 1234567890";
      break;
    case ContactType.Other:
      hoverText.value = "";
      break;
    default:
      hoverText.value = "通过这里联系我";
  }
}
// 页面挂载后执行
onMounted(() => {
  init();
  checkScrollVisibility(); // 手动检查初始状态
});

// 快速滚动到滑动卡片
/**
 * 滚动到“滑动卡片”区域的函数
 * 当用户点击页面底部的“下滑按钮”时触发
 */
const scrollToSlidingCard = () => {
  // 查找目标元素：具有 .full-page-div 和 .rounded-2xl 类的 DOM 元素
  const target = document.querySelector(".full-page-div.card-container") as HTMLElement;

  // 如果找到了目标元素，并且滚动容器 scrollbox 存在
  if (target && scrollbox) {
    // 获取目标元素距离页面顶部的偏移位置
    const targetPosition = target.offsetTop;
    // 将目标滚动位置设置为目标元素的顶部位置
    targetScrollY = targetPosition;
    // 限制目标滚动位置不能超出最大滚动范围（防止滚动过界）
    limitTargetScroll();
    // 使用 requestAnimationFrame 启动动画滚动
    // animateScroll 函数会在下一帧开始执行阻尼滚动动画
    requestAnimationFrame(animateScroll);
  }
};
//获取系统当前日期
// 计算实际的时间进度
const getTimeInfo = () => {
  const now = new Date();

  // 年度信息
  const startOfYear = new Date(now.getFullYear(), 0, 1);
  const endOfYear = new Date(now.getFullYear() + 1, 0, 1);
  const totalYearTime = endOfYear.getTime() - startOfYear.getTime();
  const elapsedYearTime = now.getTime() - startOfYear.getTime();
  const yearProgress = (elapsedYearTime / totalYearTime) * 100;
  const remainingYearTime = endOfYear.getTime() - now.getTime();

  // 月度信息
  const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
  const totalMonthTime = endOfMonth.getTime() - startOfMonth.getTime();
  const elapsedMonthTime = now.getTime() - startOfMonth.getTime();
  const monthProgress = (elapsedMonthTime / totalMonthTime) * 100;
  const remainingMonthTime = endOfMonth.getTime() - now.getTime();

  // 日信息
  const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
  const totalDayTime = endOfDay.getTime() - startOfDay.getTime();
  const elapsedDayTime = now.getTime() - startOfDay.getTime();
  const dayProgress = (elapsedDayTime / totalDayTime) * 100;
  const remainingDayTime = endOfDay.getTime() - now.getTime();

  return {
    year: {
      progress: yearProgress.toFixed(1),
      elapsed: formatDuration(elapsedYearTime),
      remaining: formatDuration(remainingYearTime),
    },
    month: {
      progress: monthProgress.toFixed(1),
      elapsed: formatDuration(elapsedMonthTime),
      remaining: formatDuration(remainingMonthTime),
    },
    day: {
      progress: dayProgress.toFixed(1),
      elapsed: formatDuration(elapsedDayTime),
      remaining: formatDuration(remainingDayTime),
    },
  };
};

// 格式化持续时间
const formatDuration = (milliseconds: number) => {
  const seconds = Math.floor(milliseconds / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);

  if (days > 0) {
    return `${days}天${hours % 24}小时`;
  } else if (hours > 0) {
    return `${hours}小时${minutes % 60}分钟`;
  } else if (minutes > 0) {
    return `${minutes}分钟${seconds % 60}秒`;
  } else {
    return `${seconds}秒`;
  }
};

const timeInfo: TimeInfo = getTimeInfo();
</script>

<template>
  <div class="viewbox min-h-screen bg-gray-100 text-gray-800">
    <main class="scrollbox container mx-auto">
      <div class="full-page-div rounded-2xl home-layer columns-2">
        <!-- 两列处理 -->
        <div class="home-col mr-20">
          <div class="flex items-center h-[80px]">
            <img style="width: 150px" class="object-cover" src="/src/assets/home/home.png" />
            <span class="top-text"> aiXiFu</span>
            <span class="sm-text"> .top</span>
          </div>
          <!-- 杂谈语言 -->
          <Layer
            style="width: 90%"
            class="mt-[20px]"
            title="宇宙一级文明狂想【哔斯卡AI影像大赛-奇想宇宙赛道】"
            description="''"
            @click="timeFlag = !timeFlag"
          />
          <!-- 联系方式 -->
          <div
            class="columns-2 h-[36px] pl-1 mt-2 contact"
            @mouseenter="handleHover(0)"
            @mouseleave="handleHover(6)"
          >
            <div
              class="contact-icon"
              style="background-position: 0 0"
              @mouseenter="handleHover(1)"
            ></div>
            <div
              class="contact-icon ml-[16px]"
              style="background-position: -59px 0"
              @mouseenter="handleHover(2)"
            ></div>
            <div
              class="contact-icon ml-[16px]"
              style="background-position: -120px 0"
              @mouseenter="handleHover(3)"
            ></div>
            <div
              class="contact-icon ml-[16px]"
              style="background-position: -175px 0"
              @mouseenter="handleHover(4)"
            ></div>
            <div
              class="contact-icon ml-[16px]"
              style="background-position: -230px 0"
              @mouseenter="handleHover(5)"
            ></div>

            <div style="line-height: 36px">
              {{ hoverText }}
            </div>
          </div>
        </div>
        <!-- 时间 右侧 -->

        <div v-if="timeFlag" class="home-col">
          <div class="columns-2">
            <Layer title="宇宙一级文明狂想" class="h-[180px]">
              <template #author> - author </template>
            </Layer>
            <Layer class="h-[180px]">
              <template #time> <liveTime :format24="false" showDate /> </template>
            </Layer>
          </div>
          <!-- 导航 -->
          <div class="w-[200px] h-[80px] rounded-xl flex items-center">
            <span class="h-[30px] pr-[10px]">
              <img src="../../assets/icon/home-nav.png" style="width: 30px" />
            </span>
            <span class="text-[16px]">网站导航</span>
          </div>

          <div class="columns-3 space-y-4">
            <navItem
              v-for="(item, index) in homeIcons"
              :key="index"
              :description="item.title"
              :url="item.icon"
              @click="navigateTo(item.url)"
            />
          </div>
        </div>
        <!-- 隐藏的替换内容  -->
        <div v-else class="home-col">
          <!-- 时间卡片容器 -->
          <TimeItem
            :hourglass="hourglass"
            :close-icon="closeIcon"
            :time-info="timeInfo"
            @close="timeFlag = true"
          />
        </div>
      </div>
      <!-- 轮播卡片 -->
      <div class="full-page-div rounded-2xl card-container"><SlidingCard :images="cards" /></div>
    </main>
  </div>

  <!-- 下滑按钮 单击后，移动到下一个视图 -->
  <div
    v-if="showScrollButton"
    class="fixed bottom-0 left-0 right-0 h-12 flex justify-center items-end pb-2 transition-transform duration-300 hover:translate-y-1"
    @click="scrollToSlidingCard"
  >
    <svg
      t="1748341911795"
      class="icon"
      viewBox="0 0 1024 1024"
      version="1.1"
      xmlns="http://www.w3.org/2000/svg"
      p-id="10584"
      width="25"
      height="25"
    >
      <path
        d="M878.276923 460.8L512 878.276923 145.723077 460.8c-19.692308-23.630769-55.138462-23.630769-78.769231-3.938462-23.630769 19.692308-23.630769 55.138462-3.938461 78.769231L472.615385 1000.369231c11.815385 11.815385 27.569231 19.692308 43.323077 19.692307s31.507692-7.876923 43.323076-19.692307l405.661539-464.738462c19.692308-23.630769 19.692308-59.076923-3.938462-78.769231-27.569231-19.692308-63.015385-19.692308-82.707692 3.938462z"
        fill="#fdfdfd"
        p-id="10585"
      ></path>
      <path
        d="M472.615385 563.2c11.815385 11.815385 27.569231 19.692308 43.323077 19.692308s31.507692-7.876923 43.323076-19.692308L960.984615 98.461538c19.692308-23.630769 19.692308-59.076923-3.938461-78.76923s-59.076923-19.692308-78.769231 3.938461L512 445.046154 145.723077 23.630769C126.030769 0 90.584615 0 66.953846 19.692308c-23.630769 19.692308-23.630769 55.138462-3.938461 78.76923L472.615385 563.2z"
        fill="#fdfdfd"
        p-id="10586"
      ></path>
    </svg>
  </div>
</template>

<style scoped lang="scss">
.full-page-div {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
  height: 100vh;
  background-color: $primary-color;
}
img {
  width: 40rem;
  margin-bottom: 5rem;
  user-select: none;
}

.scrollbox {
  position: relative;
  display: flex;
  flex-shrink: 0;
  flex-direction: column;
  align-items: center;
  width: 100%;
  transition: transform 0.15s ease;
}

.viewbox {
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  touch-action: none; /* 允许全屏滚动 */
}

.home-layer {
  padding: 0 12%;
  background-image: url("@/assets/img/bg2.jpg");
  background-position: center;
  background-size: cover;
  .home-col {
    display: flex; // 启用 Flexbox
    flex-direction: column; // 子元素纵向排列
    justify-content: center; // 垂直居中
    width: 50%;
    height: 100%;
    color: $font-color;
    .top-text {
      font-family: "homeLogo", sans-serif;
      font-size: 3rem;
    }
    .sm-text {
      font-family: "homeLogo", sans-serif;
      font-size: 1.5rem;
    }
  }
}

.contact-icon {
  display: inline-block;
  width: 35px;
  height: 33px;
  overflow: hidden;
  background-image: url("../../assets/icon/logo.png");
}

.card-container {
  width: 100%;
}

.contact:hover {
  background-color: rgba(255, 255, 255, 0.3); // 半透明白色背景
  border-radius: 5px; // 可选：添加圆角
  backdrop-filter: blur(10px); // 添加背景模糊效果
}
</style>
